package com.hemi.rhet;

import java.io.IOException;
import java.util.HashMap;

import org.androidpn.client.NotificationDetailsActivity;
import org.androidpn.client.ServiceManager;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.impl.client.AbstractHttpClient;
import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.hemi.rhet.util.AppParam;
import com.hemi.rhet.util.ApplicationContext;
import com.hemi.rhet.util.FileUtil;
import com.hemi.rhet.util.HttpUtil;
import com.hemi.rhet.util.OSInfoUtil;


public class LoginWindow extends Activity {
	private Button loginButton, exitButton;
	   private EditText mUserName;
	   ProgressDialog mDialog= null;
	   private EditText mUserPasswd;
	   private Handler mHandler = new Handler();   
	   private static final int PROCESS_BAR_SHOW=99;
	   private AppParam pdatabase =null;
	   boolean paramsUped = false;
		private static final String TAG = ActivityTopicIssure.class.getSimpleName();
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       // Start the service
       OSInfoUtil.version4Adapter();
       setContentView(R.layout.login_window);
       
       ApplicationContext.clearApplicationData();
       if(pdatabase==null)
		pdatabase=  AppParam.newInstance(LoginWindow.this );
       mUserName = (EditText)findViewById(R.id.username);
       mUserPasswd = (EditText)findViewById(R.id.userpasswd);
       if(null!=pdatabase.get("user.userId"));
       mUserName.setText(pdatabase.get("user.userId"));
       if(null!=pdatabase.get("user.password"));
       mUserPasswd.setText(pdatabase.get("user.password"));
       loginButton = (Button) findViewById(R.id.login_button);
       ((TextView) findViewById(R.id.registerTextView)).setOnClickListener(
    		   new View.OnClickListener() {
					public void onClick(View v) {
//						  ServiceManager.viewNotificationSettings(LoginWindow.this);
						
						
						 Intent i = new Intent(LoginWindow.this, NotificationDetailsActivity.class);
						LoginWindow.this.startActivity(i);	
						//showRegisterDialog();
					}
    		   }
     );
       
       
       loginButton.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
        	  // serviceManager.stopService();
        	   String userId = mUserName.getText().toString();
        	   String password = mUserPasswd.getText().toString();
        	   
        	   if(userId==null ||"".equals(userId))
               {
            	   Toast.makeText(LoginWindow.this, "用户名不能为空！",Toast.LENGTH_SHORT).show();   
            	   return ;
               }
        	   if(password==null ||"".equals(password))
               {
            	   Toast.makeText(LoginWindow.this, "密码不能为空！",Toast.LENGTH_SHORT).show();   
            	   return ;
               }
               AsyncTask<Void, Void, Object> execute = new LoginThread().execute();
           }
       });
      
   }
   
   public boolean isNull(TextView view){
	 return   view.getText()==null || view.getText().toString()==null || "".equals(view.getText().toString());
   }
   
   String  photoPath = null;
   String  serverPath = null;
   String  fileId = null;
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==R.id.reg_call_caremas){
			if( (data==null ||data.getExtras()==null|| data.getExtras().get("photoPath")==null ))
			{
				ParamUtil.showMessage(LoginWindow.this, "无图片选择！");
				return ;
			}
			   photoPath = (String)data.getExtras().get("photoPath");
			   ImageButton imageView = (ImageButton)linearlayout.findViewById(R.id.reg_call_caremas);
			imageView.setMaxHeight(50);
			imageView.setMaxWidth(50);
			Bitmap cameraBitmap2 = null;
			try {
				cameraBitmap2 = FileUtil.resizeBitmap(FileUtil.getImageBitmapAndResetRotate(photoPath),50,50);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			imageView.setImageBitmap(cameraBitmap2);
			return ;
		}
	}
   
   
   public void uploadFile2Svr() {
		 if(photoPath==null)
		 {
			 return ;
		 }
		 	String uploadMsg = "上传失败！";
	    	try {
	    		String imageInfo = FileUtil.uploadFile2Server(photoPath);
	    		HashMap mesg = ParamUtil.stringTomsgMap(imageInfo);
				if (mesg.get("resultcode").equals("0")) {
					fileId=(String)mesg.get("fileId");
					serverPath=(String)mesg.get("fileName");
					uploadMsg = "上传成功！";
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				uploadMsg += e.toString();
				Log.e("exception", e.toString());
			} catch (IOException e) {
				e.printStackTrace();
				uploadMsg += e.toString();
				Log.e("exception", e.toString());
			}
  	
}
     View linearlayout = null;
     HashMap params = null;
     String userId = null;
     Dialog	builder3 = null;
   private void showRegisterDialog(){
		LayoutInflater inflater=getLayoutInflater();
		    linearlayout= inflater.inflate(R.layout.reg_dialog, null);
		   	builder3  =	new AlertDialog.Builder(this).setIcon(R.drawable.reg_title)
				.setTitle("加入易航").setView(linearlayout).show();
		final Button regView=(Button)linearlayout.findViewById(R.id.reg_confirm);
		final ImageButton reg_call_caremas = (ImageButton)linearlayout.findViewById(R.id.reg_call_caremas);
		reg_call_caremas.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i= new Intent();
				i.setClass(LoginWindow.this, PhotoUpload.class);
				startActivityForResult(i,R.id.reg_call_caremas);
			}
		});
		regView.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				 TextView regUserId=  (TextView)linearlayout.findViewById(R.id.regUserId);
				 TextView regPassword2=  (TextView)linearlayout.findViewById(R.id.regPassword2);
				 TextView regPassword=  (TextView)linearlayout.findViewById(R.id.regPassword);
				 TextView regMail=  (TextView)linearlayout.findViewById(R.id.regMail);
				 RadioButton radioMale=  (RadioButton)linearlayout.findViewById(R.id.radioMale);
				 RadioButton radioFemale=  (RadioButton)linearlayout.findViewById(R.id.radioFemale);
				 if(isNull(regUserId))
				 {
					 Toast.makeText(LoginWindow.this, "用户ID不能为空！",Toast.LENGTH_SHORT).show();   
					 return ;
				 }
				 if(isNull(regPassword))
				 {
					 Toast.makeText(LoginWindow.this, "密码不能为空！",Toast.LENGTH_SHORT).show();   
					 return ;
				 }
				 if(isNull(regPassword2))
				 {
					 Toast.makeText(LoginWindow.this, "确认密码不能为空！",Toast.LENGTH_SHORT).show();   
					 return ;
				 }
				 
				 if(isNull(regMail))
				 {
					 Toast.makeText(LoginWindow.this, "邮箱不能为空！",Toast.LENGTH_SHORT).show();   
					 return ;
				 }
				 String gender ="F";
				 if(radioMale.isChecked())
				 {
					 gender="M";
				 }
				 if(!regPassword2.getText().toString().equals(regPassword.getText().toString())){
					 
					 Toast.makeText(LoginWindow.this, "两次 密码输入不一致！",Toast.LENGTH_SHORT).show();   
					 return ;
				 }
				
				 params = new HashMap();
				 params.put("user.userId", regUserId.getText().toString());
				 params.put("user.password", regPassword.getText().toString());
				 params.put("user.gender",gender);
				 params.put("user.mail",regMail.getText().toString());
				 userId = regUserId.getText().toString();
				 new DoregisterThread().execute();
				 if(builder3!=null)
			   	 {
			   		builder3.cancel();
			   		builder3=null;
			   	 }
			}
		});
		 
	}

   private class DoregisterThread extends AsyncTask<Void, Void, Object> {
	    private ProgressDialog mLoadingDialog;
	    @Override
	    protected void onPreExecute() {
	        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
	            mLoadingDialog.setMessage("加入进行中，请稍后...");
	        }else{
	       	 mLoadingDialog = new ProgressDialog(LoginWindow.this);
	       	 mLoadingDialog.setCancelable(false);
	       	 mLoadingDialog.setMessage("加入进行中，请稍后...");
	         mLoadingDialog.show();
	        }
	    }
	    @Override
	    protected Object doInBackground(Void... ps) {
	 	   String urlStr = new StringBuffer(ApplicationContext.DOMAIN+"/user/login_android").toString();
	 	   AbstractHttpClient httpclient = HttpUtil.getHttpClient();;
	 				 String url = HttpUtil.buildUrl("/user/doreg");
				   try {
					    uploadFile2Svr();
					    if(serverPath!=null){
							 params.put("user.photoPath",serverPath);
						}
						HashMap res=  HttpUtil.postUrl4ResultMap(url,params);
						return res;
					} catch (ClientProtocolException e) {
						e.printStackTrace();
						return e;
					} catch (IOException e) {
						e.printStackTrace();
						return e;
					} catch (JSONException e) {
						e.printStackTrace();
						return e;
					}
	 				  
	    }
	    // @Override
//	     public void onProgressUpdate(Integer... args) {
//	    	 mLoadingDialog.setProgress(args[0]);
//	     }

	    @Override
	    protected void onPostExecute(Object result) {
	          if(result instanceof HashMap)
	          {
	        	HashMap mh =(HashMap)result;
	        	if(mh.get("code")!=null && "1".equals(mh.get("code"))){ 
	        		ApplicationContext.setData("userId", userId);
	    			Intent i = new Intent(LoginWindow.this, MainTabActivity.class);
	    			i.putExtra("currentUserId", userId);
	    			startActivity(i);
	  			}else { 
	  				Toast.makeText(LoginWindow.this, "处理失败！",Toast.LENGTH_SHORT).show();            
	  			} 
	          }else if(result instanceof Exception){ 
					Toast.makeText(LoginWindow.this, "处理失败！！",Toast.LENGTH_SHORT).show();            
			  } 
	          dismissLoadingDialog();
	    }
	    
	    private void dismissLoadingDialog() {
	   	 if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
	   		 mLoadingDialog.dismiss();
	   		 mLoadingDialog = null;
	   	 }
	    }
	}
   ServiceManager   serviceManager = null;
@Override
public void finish() {
	// TODO Auto-generated method stub
	
	new AlertDialog.Builder(this)
//    .setIconAttribute(android.R.attr.alertDialogIcon)
    .setTitle(R.string.alert_loginout_title)
    .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
        	exitApp();
        }
    })
    .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {

            /* User clicked Cancel so do some stuff */
        }
    })
    .create().show();
}

private void exitApp(){
	super.finish();
	if(serviceManager!=null){
		serviceManager.stopService();
		serviceManager=null;
	}
	android.os.Process.killProcess(android.os.Process.myPid());
	System.exit(0);
}
protected void onResume() {
	// TODO Auto-generated method stub
	super.onResume();
}

@Override
	protected void onPause() {
	
	
		super.onPause();
	}
   @Override
 	protected void onStop() {
 		// TODO Auto-generated method stub

 		super.onStop();
 		
 	}
   
   
protected void onDestroy() {
	super.onDestroy();
	ApplicationContext.clearApplicationData();
	
}
   
 


@Override
protected void onRestart() {
	super.onRestart();
}



private class LoginThread extends AsyncTask<Void, Void, Object> {
    private ProgressDialog mLoadingDialog;
	String  userId ;
	String  password ;
    @Override
    protected void onPreExecute() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.setMessage("正在登陆，请稍后...");
        }else{
       	 mLoadingDialog = new ProgressDialog(LoginWindow.this);
       	 mLoadingDialog.setCancelable(false);
       	 mLoadingDialog.setMessage("正在登陆，请稍后...");
         mLoadingDialog.show();
        }
        userId =  mUserName.getText().toString();
        password = mUserPasswd.getText().toString();
    }
    @Override
    protected Object doInBackground(Void... params) {
 	   String urlStr = new StringBuffer(ApplicationContext.DOMAIN+"/user/login_android").toString();
 	   AbstractHttpClient httpclient = HttpUtil.getHttpClient();;
 			try {
 				HashMap mapparams=  new HashMap();
 	    		mapparams.put("user.userId", userId);
 	    		mapparams.put("user.password", password);
 	    		mapparams.put("user.clientType", "android");
 				String content = HttpUtil.postUrl(urlStr, mapparams);
 				HashMap mh  = HttpUtil.buildJSON2Map(content);
 				return mh;
 			} catch (ClientProtocolException e) {
 				e.printStackTrace();
 				return e;
 			} catch (IOException e) {
 				e.printStackTrace();
 				return e;
 			} catch (JSONException e) {
					e.printStackTrace();
					return e;
			}finally{
				
				
 			}
    }
    // @Override
//     public void onProgressUpdate(Integer... args) {
//    	 mLoadingDialog.setProgress(args[0]);
//     }

    @Override
    protected void onPostExecute(Object result) {
    	 Intent i = new Intent(LoginWindow.this, MainTabActivity.class);
    	  String userId = mUserName.getText().toString();
   	   	  String password = mUserPasswd.getText().toString();
          i.putExtra(KEY_LOGIN_NAME, userId);
          i.putExtra(KEY_LOGIN_PASSWD, password);
          if(result instanceof HashMap)
          {
        	HashMap mh =(HashMap)result;
        	if(mh.get("code")!=null && "1".equals(mh.get("code"))){ 
  				ApplicationContext.setData("userId", userId);
  				i.putExtra("currentUserId", userId);
  				if(pdatabase==null)
  				pdatabase=  AppParam.newInstance(LoginWindow.this );
  				pdatabase.put("user.userId", userId);
  				pdatabase.put("user.password", password);
  				pdatabase.put("carema.rsize", "90");
  				paramsUped = true;
  				pdatabase.save();
//  			  ContentResolver resolver = getContentResolver();
//  			  ContentValues values= new ContentValues();
//  			values.put("name", "user.userId");
//  			  values.put("value", userId);
//  			 resolver.insert(Uri.parse("content://com.hemi.rhet.util.ParamsDBProvider"), values);
//  			 ContentValues values2= new ContentValues();
//  			values2.put("name", "user.password");
//  			values2.put("value", password);
//  			 resolver.insert(Uri.parse("content://com.hemi.rhet.util.ParamsDBProvider"), values2);
//  			 ContentValues values3= new ContentValues();
//  			values3.put("name", "carema.rsize");
//  			values3.put("value", "180");
//  			 resolver.insert(Uri.parse("content://com.hemi.rhet.util.ParamsDBProvider"), values3);
  			
  		            serviceManager = new ServiceManager(LoginWindow.this);
  		         serviceManager.stopService();
  			     serviceManager.setNotificationIcon(R.drawable.message_resume);
  			     serviceManager.startService();
  				LoginWindow.this.startActivity(i);	
  			}else { 
  				Toast.makeText(LoginWindow.this, "用户名或密码错误！",Toast.LENGTH_SHORT).show();            
  			} 
          }else if(result instanceof ClientProtocolException){ 
				Toast.makeText(LoginWindow.this, "网络连接好像有问题哦！",Toast.LENGTH_SHORT).show();            
		  } else   { 
				Toast.makeText(LoginWindow.this, "登陆异常请重试！",Toast.LENGTH_SHORT).show();            
		  } 
          dismissLoadingDialog();
    }
  
    private void dismissLoadingDialog() {
   	 if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
   		 mLoadingDialog.dismiss();
   		 mLoadingDialog = null;
   	 }
   	 
    }
  
}



 
   
   
   
   
   
 
   
   
   
   
   
   public static final String KEY_LOGIN_NAME = "login_name";
   public static final String KEY_LOGIN_PASSWD = "login_passwd";
   public static final String KEY_LOGIN_TYPE = "login_type";

   public static boolean isCmwap = false;
}

